package com.yrk.servlet;

import com.yrk.entity.User;
import com.yrk.service.UserService;
import com.yrk.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet("/login")
public class LoginServlet extends HttpServlet{
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        request.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService = new UserServiceImpl();
        User user = userService.findUserByUserName(username);
         if(user==null){
            response.sendRedirect("login.html");
        }else if(user.getPassword().equals(password)){
             //cookie
            /* String use=URLEncoder.encode(user.getUsername(), "UTF-8");
             Cookie cookie = new Cookie("username",use);
             cookie.setMaxAge(60*60*24);
             response.addCookie(cookie);
             response.sendRedirect("impo.jsp");*/
             //session
            request.getSession().setAttribute("user",user);
            response.sendRedirect("impo.jsp");
         }else{
            response.sendRedirect("login.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
